package com.gavin.lingxi.rtclib;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;


import com.gavin.lingxi.rtclib.util.IpGetUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.gavin.lingxi.rtclib.BuildConfig.VERSION_CODE;
import static com.gavin.lingxi.rtclib.BuildConfig.VERSION_NAME;


public class RtcAnalysisUtil {
    private OkHttpClient client = new OkHttpClient();

    private static final String TAG = "RtcAnalysisUtil";
    private static final String URL = "http://bingouser.puppyrobot.com/kb8c.api/media/avtime";

    private static RtcAnalysisUtil mInstance;

    public static RtcAnalysisUtil getInstance() {
        if (mInstance == null) {
            synchronized (RtcAnalysisUtil.class) {
                if (mInstance == null) {
                    mInstance = new RtcAnalysisUtil();
                }
            }
        }
        return mInstance;
    }

    private RtcAnalysisUtil(){

    }

    public void uploadAnalysis(Context context,String user_id,String did,long startTime,long endTime,boolean isSucess,String tips){
        String deviceInfo = "品牌:"+android.os.Build.BRAND+" 型号:"+android.os.Build.MODEL+" IP:"+ IpGetUtil.getIPAddress(context);
        JSONObject dataJson = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("uid",user_id);
            jsonObject.put("did",did);
            jsonObject.put("start_time",startTime);
            jsonObject.put("end_time",endTime);
            jsonObject.put("is_success",isSucess);
            jsonObject.put("tips",tips);
            jsonObject.put("phone",deviceInfo);
            jsonArray.put(jsonObject);
            dataJson.put("data",jsonArray);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        FormBody.Builder formBody = new FormBody.Builder();
        formBody.add("data",jsonArray.toString());
        Request request =
                new Request.Builder()
                        .url(URL)
                        .addHeader("Content-Type","application/x-www-form-urlencoded")
                        .post(formBody.build())
                        .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i(TAG, "onResponse: "+response.body().string());
            }
        });


    }


    private Properties collectDeviceInfo(Context context) {
        Properties mDeviceCrashInfo = new Properties();
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                mDeviceCrashInfo.put(VERSION_NAME,
                        pi.versionName == null ? "not set" : pi.versionName);
                mDeviceCrashInfo.put(VERSION_CODE, pi.versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "Error while collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                mDeviceCrashInfo.put(field.getName(), field.get(null));
            } catch (Exception e) {
                Log.e(TAG, "Error while collect crash info", e);
            }
        }

        return mDeviceCrashInfo;
    }

    private String collectDeviceInfoStr(Context context) {
        Properties prop = collectDeviceInfo(context);
        Set deviceInfos = prop.keySet();
        StringBuilder deviceInfoStr = new StringBuilder("{\n");
        for (Iterator iter = deviceInfos.iterator(); iter.hasNext();) {
            Object item = iter.next();
            deviceInfoStr.append("\t\t\t" + item + ":" + prop.get(item)
                    + ", \n");
        }
        deviceInfoStr.append("}");
        return deviceInfoStr.toString();
    }


}
